package com.lantu.draw.framework;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.StrutsStatics;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.interceptor.StaticParametersInterceptor;
import com.opensymphony.xwork2.util.ValueStack;

public class ExceptionMappingInterceptor extends AbstractInterceptor {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private final static Logger logger = LoggerFactory.getLogger(ExceptionMappingInterceptor.class);
	@Override  
    public String intercept(ActionInvocation invocation) throws Exception {  
        try {  
        	invocation.addPreResultListener(new PreResultHandle()) ;  
        	//ValueStack stack=invocation.getStack();
            return invocation.invoke();  
        } catch (Exception e) {  
        	//logger.error("inner error",e);
            ActionSupport actionSupport = (ActionSupport) invocation.getAction();  
            exception(e, actionSupport);  
            String code="";
            String desc="";
            if(e instanceof ErrorException){
            	code=((ErrorException)e).getCode();
            	desc=((ErrorException)e).getHint();
            }
           //throw new ErrorException("操作失败");
            //把自定义错误信息   
            HttpServletRequest request = (HttpServletRequest) invocation
                            .getInvocationContext().get(StrutsStatics.HTTP_REQUEST);
            // 发送错误消息到页面  
            request.setAttribute("errorjson", "{\"code\":\""+code+"\",\"desc\":\""+desc+"\"}");
            logger.info(""+request.getAttribute("errorjson"));
            //HttpServletResponse response = (HttpServletResponse) invocation
              //      .getInvocationContext().get(StrutsStatics.HTTP_RESPONSE);
            return "jsonerror";
            //return Action.ERROR;  
        }  
    }  
  
    private void exception(Exception e, ActionSupport actionSupport) throws Exception {  
    	actionSupport.clearActionErrors();
    	actionSupport.clearErrorsAndMessages();
    	actionSupport.clearMessages();
    }  

}
